/*
 * This servlet prepares the jsp page of the handin assignments.
 * It also processes the uploaded assignment in the post method.
 */
package controllers.classes;

import classes.Breadcrumbs;
import classes.HibernateUtil;
import dao.AssignmentHandinDao;
import dao.CourseDao;
import dao.FileDao;
import dao.LessonDao;
import dao.StudentDao;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.AssignmentHandin;
import models.Course;
import models.Files;
import models.Lesson;
import models.Student;
import models.User;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Achie
 */
public class HandinController extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    /*
     * The get method loads up the content for the handin assignment page
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession ses = request.getSession();
        User user = (User) ses.getAttribute("user"); //get the user object from the session

        if (ses.getAttribute("user") == null) { //if not set, redirect to the index page
            response.sendRedirect("jsp/index.jsp");
        }

        long assignmentid = Long.parseLong(request.getParameter("id")); //assignment id
        long lessonid = Long.parseLong(request.getParameter("lessonid")); //lesson id

        HibernateUtil hu = new HibernateUtil();
        
        LessonDao ld = new LessonDao(hu.openSession());
        Lesson lesson = ld.get(lessonid); //get the lesson through the lessonid

        //prepare attributes
        request.setAttribute("course_name", lesson.getCourse().getName());
        request.setAttribute("lesson_name", lesson.getName());
        request.setAttribute("lessonid", lessonid);
        request.setAttribute("assignmentid", assignmentid);

        Course course = lesson.getCourse(); //get the course object
        
        hu.close(); //close connection
        
        // Breadcrumbs
        Breadcrumbs[] breadcrumbs = {
            new Breadcrumbs("Index", "Home"),
            new Breadcrumbs("Category", "Course catalog"),
            new Breadcrumbs("Course?courseid=" + course.getId(), course.getName()),
            new Breadcrumbs("CourseLesson?courseid=" + course.getId(), "Lessons"),
            new Breadcrumbs("LectureController?courseid=" + course.getId() + "&id=" + lesson.getId(), lesson.getName()),
            new Breadcrumbs("", "Hand-in assignment")
        };
        request.setAttribute("breadcrumbs", breadcrumbs);

        //request to the handin assignments page
        RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/handin_assignment.jsp");
        dispatcher.forward(request, response);

    }
    /*
     * The post method handles the uploaded file.
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //------------------------------------------------------------------------
        //Form proces
        //------------------------------------------------------------------------
        String name;
        String type;
        String fileName = null;
        String url;
        String path = "/uploads/handinassignments"; //the folder of the uploaded file
        String lessonid;

        //-----------------------------------------------------
        //Process the encoded form & save the file on the uploads folder
        //-----------------------------------------------------
        String folderLocation = request.getRealPath(path);
        HashMap<String, String> formParams = new HashMap<String, String>();
        // String fileName = null;
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        try {
            if (isMultipart) {

                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                // Parse the request
                List<FileItem> items = upload.parseRequest(request);

                // Process the uploaded items
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField()) {
                        // Process a regular form field
                        formParams.put(item.getFieldName(), item.getString());
                        // fileName = request.getParameter("filename");
                    } else {
                        // Process a file upload
                        fileName = item.getName();
                        File uploadedFile = new File(folderLocation + File.separator + fileName);
                        item.write(uploadedFile);
                    }
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
            throw new ServletException(fue.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }

        HibernateUtil hu = new HibernateUtil();
        //get assignment object
        long assignmentid = Long.parseLong(formParams.get("assignmentid"));

        FileDao fd = new FileDao(hu.openSession());
        Files assignment = fd.get(assignmentid);

        HttpSession ses = request.getSession();
        User user = (User) ses.getAttribute("user"); //get the user obejct from the session

        //student object
        StudentDao sd = new StudentDao(hu.openSession());
        Student stu = sd.get(user.getMember_id()); //get the student object from the user id

        //other attributes
        long id = System.nanoTime();
        url = path + "/" + fileName; 
        String description = formParams.get("description");
        lessonid = formParams.get("lessonid");
        long lesid = Long.parseLong(lessonid);

        //Create handin assignment object and save
        AssignmentHandinDao ahd = new AssignmentHandinDao(hu.openSession());
        AssignmentHandin assignmenthandin = new AssignmentHandin(id, assignment, stu, description, url);
        ahd.save(assignmenthandin); //save assignment handin
        
        //redirect to the lecture controller
        response.sendRedirect("LectureController?id=" + lesid);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
